package com.ruoyi.oos.web.controller.svg;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.oos.tag.domain.TagConfig;
import com.ruoyi.oos.tag.mapper.TagLimitdtlMapper;
import com.ruoyi.oos.tag.service.ITagConfigService;

import cn.hz.pi.api.PiApiUtil;
import cn.hz.pi.api.util.TagValue;



@Controller
@RequestMapping("/svg")
public class SvgController  extends BaseController{
	
	

	
	@RequestMapping("/realtransfer")
	public String realtransfer(Model model) {
		return "svg/SVGConvert";
	}
	
	@RequestMapping("/statictransfer")
	public String statictransfer(Model model) {
		return "svg/SVGStaticConvert";
	}
	
	@RequestMapping("/displayPic")
	 public String echart(String  point, ModelMap model) throws Exception
	    { 
		  String pitagname = point;
	      String endTime=DateUtils.getTime();
	      String startTime = DateUtils.addDateStr(new Date(), Calendar.HOUR, -8);
	      model.put("pitagname", pitagname);
	      model.put("startTime", startTime);
	      model.put("endTime", endTime);
	      	return "svg/echartData";
	    }
	    
	  @GetMapping("/getTagDetail")
	    @ResponseBody
	    public Map<String,Object> getTagDetail(TagConfig tagConfig,String startTime,String endTime,String pitagname2){
		 
	    	Map<String,Object> returnMap = new HashMap<String,Object>();
	    	
	    	try {
					if(StringUtils.isEmpty(startTime)) {
						  startTime = DateUtils.addDateStr(new Date(), Calendar.HOUR, -8);
					}
					
					if(StringUtils.isEmpty(endTime)) {
						endTime=DateUtils.getTime() ;
					}
					
					String pitagname =tagConfig.getPitagname();
					
					if(pitagname == null) {
						pitagname = "CDM158";
					}
					List<ChartBean> ychartList = new ArrayList<>();
					
					List<TagValue> list =  null;
					List<String> xdata = new ArrayList<String>();
					List<Float> ydata =  new ArrayList<Float>();
					if (pitagname != null) {
						list = PiApiUtil.getInfoList(null, pitagname, startTime, endTime, 60);//总时间);
						for (TagValue tagValue : list) {
							ydata.add(tagValue.getValue());
							xdata.add(tagValue.getTime());
					  }
					}
					
					ChartBean  bean = new ChartBean();
					bean.setName(pitagname);
					bean.setSmooth(true);
					bean.setType("line");
					bean.setData(ydata);
					ychartList.add(bean);
					
					if(StringUtil.isNotEmpty(pitagname2) && pitagname2.length()>2) {
						String[] points = pitagname2.split(",");
						for (String point : points) {
							ydata =  new ArrayList<Float>();
							list= PiApiUtil.getInfoList(null, point, startTime, endTime, 60);//总时间);
							for (TagValue tagValue : list) {
								ydata.add(tagValue.getValue());
						     }
							 bean = new ChartBean();
						    	bean.setName(point);
						    	bean.setSmooth(true);
						    	bean.setType("line");
						    	bean.setData(ydata);
						    	ychartList.add(bean);
							
					}
					}
					
					
					String  legend ="["+pitagname+","+pitagname2+"]";
					String title = startTime +"--"+endTime;
					returnMap.put("legend", legend);
					returnMap.put("title", title);
					returnMap.put("xchart", xdata);
					returnMap.put("ychartList", ychartList);
				} catch (Exception e) {
					e.printStackTrace();
					returnMap.put("code", "0");
					return returnMap;
				}
	    	
	    	returnMap.put("code", "1");
	    	
	    	return returnMap;
	    }
	    
	
	
	
	
	/**
	 * 实时和统计SVG
	 * @param model
	 * @param queryName
	 * @param currentPage
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Model model, String file1, String file2) {
		
		model.addAttribute("realFile",file1);
		model.addAttribute("staticFile",file2);
		return "svg/SVG";
	}
	
	/**
	 * 实时SVG
	 * @param model
	 * @param file	svg文件名
	 * @return
	 */
	@RequestMapping("/realTime")
	public String realTime(Model model,String file) {
		StringBuilder builder = this.getSVGFile(file);
		model.addAttribute("svgContent",builder);
		model.addAttribute("fileName",file);
		return "svg/SVGRealTime";
	}
	
	/**
	 * 实时刷新svg图测点数据
	 * @param paramStr
	 * @return
	 */
	@RequestMapping(value = "/getValue")
	@ResponseBody
	public String getValue(String paramStr) {
		System.out.println("paramStr"+paramStr);
		JSONArray paramArray = JSON.parseArray(paramStr);
		List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
		String server ="";
		 List<String> a = new ArrayList<String>();
		for (int i = 0; i < paramArray.size(); i++) {
			JSONObject jsonObject = paramArray.getJSONObject(i);
			// PI服务地址
			server = jsonObject.getString("servers");
			String point = jsonObject.getString("point").toLowerCase();
			 a.add(point);
		}
		
//		String piString = "";
//		for (String set : PiServerSet) {
//			piString = piString + set + "#";
//			for (int i = 0; i < paramArray.size(); i++) {
//				JSONObject jsonObject = paramArray.getJSONObject(i);
//	
//				// PI服务地址
//				String servers = jsonObject.getString("servers");
//				// 测点名
//				String point = jsonObject.getString("point").toLowerCase();
//				System.out.println("point" +point);
//				if (set.equals(servers)) {
//					piString = piString + point + ",";
//				}
//			}
//			piString = piString.substring(0,piString.length()-1);
//			piString = piString + ";";
//		}
		
//		String[] piStringSplit = piString.split(";");
		//		for(String str : piStringSplit) {
		//			String[] temp = str.split("#");
			
			// PI服务地址
		//			String server = temp[0];
		//			String[] pointTemp = temp[1].split(",");
		//	Set<String> set = new HashSet<String>();
			
		//	CollectionUtils.addAll(set, pointTemp);
			
		 //	List<String> a = new ArrayList<String>(set);
		
		Map<String, String> map = new HashMap<String, String>();
//			float[] values=	PiApiUtil.getInfoValuesnew(null, a);
//				int i =0;
//				for (String string : a) {
//					map = new HashMap<String, String>();
//					map.put("server", server);
//					map.put("point", string);
//					map.put("state", "0");
//					map.put("engunits","");
//					map.put("value", values[i]+"");
//					i++;
// 					resultList.add(map);	
//				}
				Map<String, TagValue> test=	PiApiUtil.getInfoValues(null, a);
				System.out.println(test);
				if (null != test && !test.isEmpty()) {
					for (String key : test.keySet()) {
						map = new HashMap<String, String>();
						map.put("server", server);
						map.put("point", key);
						map.put("state", test.get(key).getState()+"");
						map.put("engunits",PiApiUtil.getTagUnit(null,key));
						map.put("value", test.get(key).getValue().toString());
						resultList.add(map);	
					}
				}	
				
		 
		
		return JSON.toJSONString(resultList);
	}
	
	

	


	private StringBuilder getSVGFile(String file){
	    InputStream in = null;
	    StringBuilder builder = null;
	    try {
	    	String svgurl = AddressUtil.getProperty("apacheSVG");
	    	System.out.println(svgurl);
	        //连接
	        URL url = new URL(svgurl + file);
	        URLConnection uc = url.openConnection();
	         
	        //获取读入流
	        in = uc.getInputStream();
	        //放入缓存流
	        InputStream raw = new BufferedInputStream(in);
	        //最后使用Reader接收
	        Reader r = new InputStreamReader(raw,"utf-8");
	         
	        // 获取svg文件内容
	        int c;
	        builder = new StringBuilder();
	        while((c = r.read())!=-1){
	            builder.append((char)c);
	        }
	    } catch (MalformedURLException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally{
	        try {
	            if(in!=null){
	                in.close();
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
	    
	    return builder;
	}  
	


}
